package com.example.coursedesign.ui.home.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.coursedesign.R;
import com.example.coursedesign.ui.home.addRemind;
import com.example.coursedesign.ui.home.dao.mRemindDao;
import com.example.coursedesign.ui.home.entity.mRemind;
import com.example.coursedesign.ui.home.medicineRemind;

import java.sql.SQLException;
import java.util.List;

public class RemindAdapter extends BaseAdapter {
    private Context context;
    private List<mRemind> remindList;
    private mRemindDao remindDao;

    public RemindAdapter(Context context, List<mRemind> remindList) {
        this.context = context;
        this.remindList = remindList;
        this.remindDao = new mRemindDao();
    }

    @Override
    public int getCount() {
        return remindList.size();
    }

    @Override
    public Object getItem(int position) {
        return remindList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_remind, parent, false);
        }

        final mRemind remind = remindList.get(position);

        ImageView imgPic = convertView.findViewById(R.id.img_pic);
        TextView tvClock = convertView.findViewById(R.id.tv_clock);
        TextView tvName = convertView.findViewById(R.id.tv_name);
        TextView tvNumber = convertView.findViewById(R.id.tv_number);
        TextView tvDetail = convertView.findViewById(R.id.tv_detail);
        Button btUpdate = convertView.findViewById(R.id.bt_update);
        Button btUsed = convertView.findViewById(R.id.bt_used);

        // 设置数据
        if (remind.getPicture() != null && !remind.getPicture().isEmpty()) {
            try {
                // 使用 Glide 加载 Base64 编码的图片字符串到 ImageView
                String base64Image = "";
                if (remind.getPicture().contains(",")) {
                    base64Image = remind.getPicture().split(",", 2)[1];
                } else {
                    base64Image = remind.getPicture();
                }
                byte[] imageBytes = Base64.decode(base64Image, Base64.DEFAULT);
                Glide.with(context)
                        .asBitmap()
                        .load(imageBytes)
                        .apply(new RequestOptions().override(300, 300)) // 设置目标尺寸
                        .into(imgPic);
                imgPic.setVisibility(View.VISIBLE); // 确保ImageView是可见的
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(context, "图片加载失败", Toast.LENGTH_SHORT).show();
                imgPic.setVisibility(View.GONE); // 如果加载失败，隐藏ImageView
            }
        } else {
            imgPic.setVisibility(View.GONE); // 没有图片时隐藏ImageView
//            imgPic.setImageResource(R.drawable.add); // 或者设置默认图片
        }

        tvClock.setText(remind.getRemindTime());
        tvName.setText(remind.getName());
        tvNumber.setText(remind.getNumber());
        tvDetail.setText(remind.getDetail());

        // 设置按钮点击事件
        btUpdate.setOnClickListener(v -> {
            Intent intent = new Intent(context, addRemind.class);
            intent.putExtra("remind", remind);
            context.startActivity(intent);
        });

        btUsed.setOnClickListener(v -> {
            new Thread(() -> {
                try {
                    remind.setStatus("已服用");
                    boolean isUpdated = remindDao.update(remind);
                    if (isUpdated) {
                        ((Activity) context).runOnUiThread(() -> {
                            Toast.makeText(context, "已标记为已服用", Toast.LENGTH_SHORT).show();
                            // 刷新列表
                            ((medicineRemind) context).new FetchDataAsyncTask().execute();
                        });
                    } else {
                        ((Activity) context).runOnUiThread(() -> Toast.makeText(context, "更新失败", Toast.LENGTH_SHORT).show());
                    }
                } catch (java.sql.SQLException e) {
                    e.printStackTrace();
                    ((Activity) context).runOnUiThread(() -> Toast.makeText(context, "更新失败", Toast.LENGTH_SHORT).show());
                }
            }).start();
        });

        return convertView;
    }

    public void setRemindList(List<mRemind> remindList) {
        this.remindList = remindList;
        notifyDataSetChanged();
    }
}